﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using PJ.Business;
using Microsoft.Practices.Composite.Events;
using System.Collections.ObjectModel;

namespace PJ.Presentation
{
    public abstract class BusinessObjectListViewModel<T> : BaseViewModel, IBusinessObjectListViewModel<T>
        where T: class, IBusinessObject
    {
        protected BusinessObjectListViewModel(IView view, IEventAggregator aggregator, IBusinessObjectService<T> service)
            : base(view, aggregator)
        {
            if (service == null)
                throw new ArgumentNullException("service");
            m_Service = service;
        }


        public virtual void BusinessObjectListChange(IEnumerable<string> globalIdList)
        {
            SetValues(globalIdList);
        }

        public ObservableCollection<T> BusinessObjectList
        {
            get { return (ObservableCollection<T>)ThreadUnsafeGetValue(BusinessObjectListProperty); }
            set { ThreadUnsafeSetValue(BusinessObjectListProperty, value); }
        }



        /// <summary>
        /// Set a new list
        /// </summary>
        /// <param name="globalIdList">list of new object global ids</param>
        public virtual void SetValues(IEnumerable<string> globalIdList)
        {
            if (BusinessObjectList == null)
            {
                BusinessObjectList = new ObservableCollection<T>();
                foreach (string globalId in globalIdList)
                {
                    BusinessObjectList.Add(Service.GetData(globalId));
                }
            }
        }

        /// <summary>
        /// Get the model list content
        /// </summary>
        /// <returns>List of object global ids</returns>
        public virtual IEnumerable<string> GetValues()
        {
            throw new NotImplementedException();
        }


        protected IBusinessObjectService<T> Service
        {
            get
            {
                if (m_Service == null)
                    throw new ArgumentNullException();
                return m_Service;
            }
        }

        #region Fields


        private readonly IBusinessObjectService<T> m_Service;

        public static readonly DependencyProperty BusinessObjectListProperty =
            DependencyProperty.Register("BusinessObjectList", typeof(ObservableCollection<T>), typeof(BusinessObjectListViewModel<T>), new UIPropertyMetadata(""));

        #endregion

    }
}
